<template>
    <div>
        <div class="panel-subs-body-box-hd">
            <div
                class="hd"
                :style="{ width: monitorType.includes('2') || monitorType.includes('3') ? ' calc(100% - 320px)' : ' calc(100% - 250px)' }"
            >
                <span :title="pItem.moduleName" class="body-box-hd-span">{{ pItem.moduleName }}</span>
            </div>
            <div class="panel-subs-body-box-icon">
                <span v-if="monitorType.includes('2') || monitorType.includes('3')">
                    成交口径：<el-switch
                        v-model="moduleSearchParam.resultType"
                        size="mini"
                        active-color="#409eff"
                        inactive-color="#eee"
                        active-value="3"
                        inactive-value="2"
                        :disabled="disSwitch"
                        @change="resultTypeChange"
                        style="margin-right: 4px"
                    ></el-switch>
                </span>
                <el-button size="mini" type="primary" :loading="refreshLoading" @click="refreshModule">
                    {{ refreshLoading ? '计算中' : '刷新' }}
                </el-button>
                <el-button size="mini" type="primary" @click="searchModule">查询</el-button>
                <el-button size="mini" type="primary" @click="loadout">导出</el-button>
                <!-- <div class="zc-icon img-dachuang"></div> -->
                <!-- <div class="zc-icon img-xiaochuang"></div> -->
                <div class="zc-icon img-guanbi" title="关闭" @click="onCloseTable"></div>
            </div>
        </div>
        <div class="panel-subs-body-box-main">
            <el-table
                :data="moduleData"
                height="calc(50vh - 155px)"
                v-loading="isFullScreen === null ? moduleLoading : moduleLoading && isFullScreen == pItem.moduleCode"
                size="mini"
                row-key="entryCode"
                border
                highlight-current-row
                :default-sort="{ prop: sortProp, order: sortOrder }"
                @sort-change="changeTableSort"
                @selection-change="selectionChange"
                :ref="`triggerScreen - ${pItem.moduleCode}`"
            >
                <el-table-column type="selection" :reserve-selection="true" width="40"></el-table-column>
                <el-table-column
                    v-for="(col, index) in columns"
                    :key="col.val + col.name + index"
                    :prop="col.val"
                    :label="col.name"
                    :width="col.width"
                    :show-overflow-tooltip="col.showOverflowTooltip"
                    :sortable="col.sortable"
                    :min-width="col.minWidth"
                >
                    <template slot-scope="scope">
                        <span v-if="col.val === 'thresholdValue'">
                            {{ formatThresholdValue(scope.row) }}
                        </span>
                        <span v-else-if="col.val === 'thresholdType'">
                            <StatusTag :code="scope.row.thresholdType"></StatusTag>
                        </span>

                        <span v-else-if="col.val === 'calculateValue'">
                            <span
                                v-if="scope.row.calculateValue != null"
                                :style="{
                                    textDecoration: 'underline',
                                    textDecorationColor: ThresholadEntryColor[scope.row.thresholdType],
                                    color: ThresholadEntryColor[scope.row.thresholdType],
                                    cursor: 'pointer',
                                }"
                                @click="openEntryResultDetail(scope.row)"
                                slot="reference"
                            >
                                {{ formatCalculateValue(scope.row) || '--' }}
                            </span>
                            <span v-else>--</span>
                        </span>
                        <span v-else-if="col.val === 'calculateTime'">
                            {{ timeFormat(scope.row.calculateTime) || '--' }}
                        </span>
                        <span
                            v-else-if="col.val === 'handleStatus'"
                            :style="{
                                color: scope.row.handleStatus == '1' ? '#d9001b' : scope.row.handleStatus == '2' ? '#101d29' : '#bfbfbf',
                            }"
                        >
                            {{ handleStatusFormatter(scope.row) }}
                        </span>
                        <span v-else>{{ scope.row[col.val] || '--' }}</span>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 触警屏查询页面 -->
        <yh-dialog :visible.sync="searchModuleVisible" title="模块数据查询" drag :close-on-click-modal="false" width="600px">
            <el-form label-width="100px" size="mini" ref="moduleSearchRef" :model="moduleSearchParam">
                <el-form-item label="条目编号" prop="entryCodes">
                    <el-input placeholder="支持','分割" size="mini" v-model="entryCodes" style="width: calc(100% - 100px)"></el-input>
                    <!-- @change="handleEntryCodeList" -->
                    <el-checkbox
                        v-model="moduleSearchParam.accurateSelect"
                        size="mini"
                        style="width: 87px; border: 1px solid #ccc; height: 26px; line-height: 22px; padding: 2px; margin-left: 8px"
                        >准确搜索</el-checkbox
                    >
                </el-form-item>
                <el-form-item label="风险说明" prop="entryName">
                    <el-input v-model="moduleSearchParam.entryName" style="width: 100%"></el-input>
                </el-form-item>

                <el-form-item label="触警类型" prop="thresholdType">
                    <el-select v-model="moduleSearchParam.thresholdTypes" style="width: 42%" clearable collapse-tags filterable multiple>
                        <el-option v-for="item in ThresholdTypeDict" :key="item.dictKey" :value="item.dictKey" :label="item.dictKeyName"> </el-option>
                    </el-select>
                    <!--
                    <span> 处理状态 </span>
                    <el-select v-model="moduleSearchParam.handleStatus" style="width: 43%" clearable>
                        <el-option v-for="(value, key) in handleStatusAll" :key="key" :value="key" :label="value"> </el-option>
                    </el-select>
                    -->
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="resetSearchModule"> 重 置 </el-button>
                <el-button size="mini" @click="searchModuleVisible = false"> 取 消 </el-button>
                <el-button size="mini" type="primary" @click="submitSearchModule"> 确 定 </el-button>
            </div>
        </yh-dialog>
    </div>
</template>
<script lang="ts">
import StatusTag from '@/pages/risk-measure/components/status-tag.vue';
import DictionConstUtil from '@/utils/diction-const-util';
import { downLoadFile } from '@/utils/request';
import { checkPermission, getConfigItem, numberFormat, timeFormat, numberFormatXDAY, numberFormatCIB, unitShow } from '@/utils/tools';
import { Vue, Component, Prop, Watch } from 'vue-property-decorator';
import { manualStartByModuleCode, rateOfProgress } from '../api';

@Component({
    name: 'TriggerScreen',
    components: {
        StatusTag,
    },
})
export default class TriggerScreen extends Vue {
    @Prop() pItem: any; // 模块信息

    @Prop() searchParam: any;

    @Prop() reload;

    @Prop({ default: null }) isFullScreen;

    @Prop() thresholdTypeKeys: any[];

    @Prop() totalDynamicColumn: any[]; // 页面布局

    @Prop() panelDetailDataSource: any[];
    // 监控屏计算模式配置: 1-从严(有利成交、不利指令)、2-非从严(全部指令值)、3-成交(全部成交值)
    @Prop() monitorType: string[];

    timeFormat = timeFormat;
    numberFormat = numberFormat;
    numberFormatXDAY = numberFormatXDAY;

    isFirst: boolean = true;

    private searchModuleVisible: boolean = false; // 模板搜索页面

    private entryCodes: string = ''; // 模板条目编号显示值

    moduleData: any = [];

    moduleLoading: boolean = false;

    private sortProp: string = 'C_HANDLE_STATUS'; // 排序字段

    private sortOrder: string = 'ASC'; // 排序方式

    private columns: any[] = [];

    private ThresholdTypeDict = DictionConstUtil.PojoToList(DictionConstUtil.ThresholdType).filter(item => item.dictKey != '4');

    TimeSendMessage: any = null;

    randValue = 30;

    currentLimiting: boolean = false; // 限流

    WEB_DOCKING = getConfigItem('WEB_DOCKING');

    // 颜色字典
    private ThresholadEntryColor = {
        '0': '#222',
        '1': '#222',
        '2': '#222',
        '3': '#d9001b',
        '4': '#222',
    };

    // 状态
    private handleStatusAll = {
        '1': '待处理',
        '2': '已处理',
        '3': '无需处理',
    };

    // 符号字典
    private CompareDirection = {
        '0': '>',
        '1': '<',
        '2': '>=',
        '3': '<=',
        '4': '=',
        '5': '<>',
        '6': ' ',
    };

    obj = {
        moduleCode: '',
        tableKeys: [],
        // thresholdTypes: [],
        moduleSearchParam: {},
        selectionValues: [],
        key: 1,
    };

    // 模块搜索
    private moduleSearchParam = {
        accurateSelect: true,
        entryCodes: [],
        entryName: '',
        fundCodes: [],
        fundGrCodes: [],
        handleStatus: '',
        moduleCode: '',
        thresholdTypes: ['3'],
        useEntryPanelCode: '',
        resultType: '1',
        sort: '',
    };

    initial: boolean = true; // 是否最初状态
    isRefSelect: boolean = false; // 是否是全部取消勾选
    operateType: string = '';
    selectionKey: number = 0; // 触发勾选

    disSwitch: boolean = false;

    refreshLoading: boolean = false; // #9342 监控屏进度条
    timer: any = null;

    // 重新点击查询时
    @Watch('reload')
    async reloadData() {
        this.moduleSearchParam = {
            ...this.moduleSearchParam,
            thresholdTypes: this.thresholdTypeKeys,
            entryCodes: this.entryCodes ? this.entryCodes.split(',') : [],
        };

        try {
            this.moduleData = await this.getModule();
        } finally {
            if (this.moduleData.length) {
                let re = this.$refs['triggerScreen - ' + this.pItem.moduleCode] && (this.$refs['triggerScreen - ' + this.pItem.moduleCode] as any);
                this.isRefSelect = true;
                re.clearSelection();
                this.isRefSelect = false;
                this.$refs['triggerScreen - ' + this.pItem.moduleCode] &&
                    (this.$refs['triggerScreen - ' + this.pItem.moduleCode] as any).toggleAllSelection();
            } else {
                this.selectionChange([]);
            }
            this.TimeSendMessage && clearInterval(this.TimeSendMessage);
            this.setT();
        }
    }
    // tableKey: number = -1;
    // 页面布局
    @Watch('totalDynamicColumn', { immediate: true, deep: true })
    onWatchTotalColumn() {
        if (this.totalDynamicColumn && this.totalDynamicColumn.length > 0) {
            this.columns = this.totalDynamicColumn;
            // this.tableKey++;
            // this.$nextTick(() => {
            //     (this.$refs['triggerScreen - ' + this.pItem.moduleCode] as any).doLayout();
            //     console.log((this.$refs['triggerScreen - ' + this.pItem.moduleCode] as any).debouncedUpdateLayout);
            // });
        }
    }

    async mounted() {
        this.randValue = Math.floor(Math.random() * (60 - 30) + 30);

        this.obj.moduleCode = this.pItem.moduleCode;
        this.moduleSearchParam.thresholdTypes = this.thresholdTypeKeys;

        if (this.monitorType.includes('2') || this.monitorType.includes('3')) {
            if (this.monitorType.length === 1) {
                this.moduleSearchParam.resultType = this.monitorType[0];
                this.disSwitch = true;
            } else {
                if (this.WEB_DOCKING === 'MAXWEALTH') {
                    this.moduleSearchParam.resultType = '2';
                } else {
                    this.moduleSearchParam.resultType = '3';
                }
                this.disSwitch = false;
            }
        }

        try {
            this.moduleData = await this.getModule();
            this.$nextTick(() => {
                this.$refs['triggerScreen - ' + this.pItem.moduleCode] &&
                    (this.$refs['triggerScreen - ' + this.pItem.moduleCode] as any).toggleAllSelection();
            });
        } finally {
            this.TimeSendMessage && clearInterval(this.TimeSendMessage);
            this.setT();
        }

        this.getRateOfProgress();
        this.timer = setInterval(() => this.getRateOfProgress(), 20000);
    }

    // 设置定时器
    setT() {
        this.TimeSendMessage = setInterval(async () => {
            await this.handle();
        }, (this.randValue + this.pItem.index) * 1000);
    }

    async handle() {
        if (this.searchParam.moduleCodes.includes(this.pItem.moduleCode)) {
            this.moduleData.length > 0 && this.obj.key++;
            this.obj.moduleSearchParam = JSON.parse(JSON.stringify(this.moduleSearchParam));
            this.moduleData = await this.getModule('autoRefresh');
            // 是否人工勾选
            let manualSeleted = this.obj.tableKeys.length > this.obj.selectionValues.length;
            if (this.currentLimiting && this.moduleData.length && !manualSeleted) {
                this.$refs['triggerScreen - ' + this.pItem.moduleCode] &&
                    (this.$refs['triggerScreen - ' + this.pItem.moduleCode] as any).toggleAllSelection();
                this.currentLimiting = false;
                this.selectionKey++;
            } else if (this.initial && this.moduleData.length && !manualSeleted) {
                let re = this.$refs['triggerScreen - ' + this.pItem.moduleCode] && (this.$refs['triggerScreen - ' + this.pItem.moduleCode] as any);
                this.isRefSelect = true;
                re.clearSelection();
                this.isRefSelect = false;
                this.$refs['triggerScreen - ' + this.pItem.moduleCode] &&
                    (this.$refs['triggerScreen - ' + this.pItem.moduleCode] as any).toggleAllSelection();
                this.selectionKey++;
            } else {
                this.$emit('screen-change', JSON.parse(JSON.stringify(this.obj)), 'autoRefresh');
            }
        }
    }

    beforeDestroy() {
        if (this.TimeSendMessage) {
            this.TimeSendMessage && clearInterval(this.TimeSendMessage);
            this.TimeSendMessage = null;
        }

        if (this.timer) {
            this.timer && clearInterval(this.timer);
            this.timer = null;
        }
    }

    // 查询
    searchModule(): void {
        this.searchModuleVisible = true;
    }

    // 取消模块查询
    cancelSearchModule() {
        this.searchModuleVisible = false;
    }
    key: number = 0;

    // 勾选
    @Watch('selectionKey', { immediate: true, deep: true })
    onWatchSelectionKey() {
        this.operateType = 'autoRefresh';
        // 测试
        console.error(this.selectionKey, 'this.selectionKey---------------onWatchSelectionKey');
    }

    // 勾选
    selectionChange(values) {
        // 测试
        console.error(this.operateType, this.selectionKey, 'this.selectionKey-------------------selectionChange');
        if (this.isRefSelect) {
            return;
        }
        console.log(this.key++, 'key');
        // 最先开始会执行一次
        this.obj.selectionValues = values;
        this.obj.moduleSearchParam = this.moduleSearchParam;
        // this.$emit('screen-change', JSON.parse(JSON.stringify(this.obj)), '');
        this.$emit('screen-change', JSON.parse(JSON.stringify(this.obj)), this.operateType);
        this.operateType = '';
    }

    // 关闭表格
    onCloseTable() {
        this.$emit('onCloseTable', this.pItem.moduleCode);
    }

    // 确认模块查询
    async submitSearchModule() {
        this.initial = false;
        this.cancelSearchModule();

        this.moduleSearchParam.entryCodes = this.entryCodes ? this.entryCodes.split(',') : [];

        this.moduleData = await this.getModule();

        this.obj.moduleSearchParam = this.moduleSearchParam;
        this.$emit('screen-change', JSON.parse(JSON.stringify(this.obj)), '');
    }

    // 重置模块查询
    resetSearchModule() {
        this.entryCodes = '';
        (this.$refs.moduleSearchRef as any).resetFields();
        this.moduleSearchParam.handleStatus = '';
    }

    // 获取模板
    private getModule(operateType?: string) {
        // operateType 操作类型 autoRefresh:定时刷新，
        this.moduleLoading = true;
        this.moduleSearchParam.moduleCode = this.pItem.moduleCode;
        this.moduleSearchParam.useEntryPanelCode = this.searchParam.useEntryPanelCode;
        this.moduleSearchParam.fundCodes = this.searchParam.fundCodes;
        this.moduleSearchParam.fundGrCodes = this.searchParam.fundGrCode;

        this.getMemory();

        return new Promise((resolve, reject) => {
            this.$axios({ url: '/panorama/module/result', method: 'post', data: this.moduleSearchParam, headers: { operateType: operateType } })
                // .post('/panorama/module/result', this.moduleSearchParam)
                .then((res: any) => {
                    this.moduleLoading = false;
                    let retValue: any[] = [];
                    // 可能存在限流的情况导致返回空对象
                    if (res && Object.prototype.toString.call(res) === '[object Array]' && res.length) {
                        retValue = res;
                        this.obj.tableKeys = (res || []).map(item => item.entryCode);
                    } else {
                        // 限流
                        this.currentLimiting = true;
                    }
                    resolve(retValue);
                })
                .catch(err => {
                    this.moduleLoading = false;
                    reject(err);
                });
        });
    }

    moduleSortObject = {
        handleStatus: 'C_HANDLE_STATUS',
        entryCode: 'C_ENTRY_CODE',
        entryName: 'C_ENTRY_NAME',
        compareType: 'C_COMPARE_TYPE',
        thresholdValue: 'N_THRESHOLD_VALUE',
        calculateValue: 'N_CALCULATE_VALUE',
        calculateTime: 'D_CALCULATE_TIME',
        thresholdType: 'C_THRESHOLD_TYPE',
        complianceNum: 'complianceNum',
        warningNum: 'warningNum',
        examinationNum: 'examinationNum',
        prohibitNum: 'prohibitNum',
    };

    // 排序改变
    private async changeTableSort(column) {
        this.sortProp = column.prop;
        this.sortOrder = column.order;
        let sortType = column.order == 'ascending' ? 'ASC' : column.order == 'descending' ? 'DESC' : '';
        this.moduleSearchParam.sort = this.moduleSortObject[column.prop] + ' ' + sortType;
        this.moduleData = await this.getModule();
    }

    // 导出
    loadout() {
        downLoadFile({
            url: '/panorama/module/result/export',
            method: 'post',
            data: this.moduleSearchParam,
        });
    }

    // 格式化字段(处理状态)
    handleStatusFormatter(value) {
        return this.handleStatusAll[value.handleStatus];
    }

    // 实际值明细
    openEntryResultDetail(row) {
        if (!checkPermission('B_0342')) {
            console.log('onClick: 该账号无明细数据查看权限!');
            return;
        }
        this.$emit('openEntryResultDetail', { row: row, pItem: this.pItem, type: 'module' });
    }

    // 成交口径改变
    async resultTypeChange(curValue) {
        this.moduleData = await this.getModule();

        this.obj.moduleSearchParam = this.moduleSearchParam;
        this.$emit('screen-change', JSON.parse(JSON.stringify(this.obj)), '');
    }

    refreshModule() {
        this.$confirm('是否重新计算模块' + this.pItem.moduleCode + '?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info',
        }).then(() => {
            return new Promise((resolve, reject) => {
                manualStartByModuleCode(this.pItem.moduleCode)
                    .then((res: any) => {
                        this.handle();
                        // 轮询刷新进度
                        this.refreshLoading = true;
                        this.getRateOfProgress();
                        if (!this.timer) {
                            this.timer = setInterval(() => this.getRateOfProgress(), 20000);
                        }
                        this.yh_message_success(`模块${this.pItem.moduleCode}计算发起成功！`);
                        resolve(res);
                    })
                    .catch(err => {
                        reject(err);
                    });
            });
        });
    }

    /**
     * 定时查询 重新计算进度  0计算中 1已完成
     */
    getRateOfProgress(): void {
        console.log(this.pItem.moduleCode, 'this.pItem.moduleCode?');

        rateOfProgress(this.pItem.moduleCode).then((res: any) => {
            // res = Math.random() < 0.5 ? 0 : 1;
            console.warn(res, 'res');

            if (res == '1') {
                if (this.refreshLoading) {
                    this.getModule();
                }
                this.refreshLoading = false;
                if (this.timer) {
                    this.timer && clearInterval(this.timer);
                    this.timer = null;
                }
            } else {
                this.refreshLoading = true;
            }
        });
    }

    formatThresholdValue(row): string {
        if (row.thresholdValue || row.thresholdValue == 0) {
            return this.CompareDirection[row.compareType] + numberFormatCIB(row.thresholdValue, row.unit, 'thresholdValue') + unitShow(row.unit);
        }
        return '--';
    }

    formatCalculateValue(row) {
        if (row.calculateValue || row.calculateValue == 0) {
            return numberFormatCIB(row.calculateValue, row.unit) + unitShow(row.unit);
        }
        return '--';
    }

    /**
     * 华泰崩溃预警
     */
    getMemory(): void {
        const memory = (performance as any).memory;
        const usedMemory = memory.usedJSHeapSize / 1024 / 1024; // 转换为MB
        const totalMemory = memory.totalJSHeapSize / 1024 / 1024; // 转换为MB
        const memoryLimit = memory.jsHeapSizeLimit / 1024 / 1024; // 转换为MB

        console.log('已使用内存：' + usedMemory + 'MB');
        console.log('总内存：' + totalMemory + 'MB');
        console.log('内存限制：' + memoryLimit + 'MB');

        // if (usedMemory > 1900) {
        //     removeUser();
        //     router.push({ path: '/login' });
        // }
    }
}
</script>
<style lang="scss" scoped>
.panel-subs-body-box-hd {
    position: relative;
    line-height: 40px;
    height: 40px;
    text-align: center;
    border-bottom: 1px solid #c8c8c8;
}
/deep/ .el-table__body-wrapper {
    min-height: calc(100% - 48px) !important;
}
</style>
